<?php
declare( strict_types = 0 );
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\Cache;
use app\model\OrderModel;
use app\model\CatModel;
use app\model\UserModel;
use app\model\DeptModel;
use app\model\DeliveryModel;
use app\Common;

class Order {
    //常用数据表内容 及常用字典

    var $cat = [];
    var $dept = [];
    var $users = [];
    var $bg;
    var $sys;
    var $stars = array( 0 => '', 1 => '★☆☆☆☆', 2 => '★★☆☆☆', 3 => '★★★☆☆', 4 => '★★★★☆', 5 => '★★★★★' );

    //[ 'name', 'english name', 'next statue', 'view name' ]
    var $status = array(
        '1' => array( '新单', 'New order', '2', '确认' ),
        '2' => array( '已确认', 'Checked', '3', '发货中' ),
        '3' => array( '已发货', 'Delivering', '4', '完成' ),
        '4' => array( '已完成', 'Finished', '5', '' ),
        '6' => array( '已退货', 'Return', '', '' ),
        '10' => array( '客户取消', 'Canceled by Customer ', '0', '' ),
        '20' => array( '供应商取消', 'Canceled by supplier', 0, '' )
    );
    var $discount = [];
    var $payment = array( 'wx' => '微信', 'alipay' => '支付宝', 'cash' => '现金' );
    var $type = array( '1' => '客户下单', '2' => '转手订单' );
    var $status_delivery = array( '1' => '待确认', '2' => '已确认', '3' => '已取消' );

    //构造器

    public function __construct() {
        $catM = new CatModel();
        $this->cat = $catM->catTree( 1 );
        $um = new UserModel();
        $this->users = $um->getAll();
        $dm = new DeptModel();
        $this->dept = $dm->getAll();

        for ( $dis = 100; $dis > 50; $dis -= 5 ) {
            $this->discount[] = [ 'value' => $dis / 100, 'desc' => $dis . '%' ];
        }
        $this->sys = Db::table( 'sys' )->find( 1 );

    }

    //商品

    public function goods_list() {
        $list = Db::table( 'goods' )->where( 'status', 1 )->order( 'id' )->select()->toArray();
        return json( $list );
    }

    //订单流程中查询, 用不同的状态区分所处流程

    public function index( $status = '' ) {
        $uid = Session::get( 'logonid' );
        if ( empty( $uid ) )
        header( 'location:/index.php/login' );

        $all = Request::param();

        $sdate = !empty( $all[ 'sdate' ] ) ? $all[ 'sdate' ] : '';
        $edate = !empty( $all[ 'edate' ] ) ? $all[ 'edate' ] : date( 'Y-m-d', time() );
        if ( $edate < $sdate )
        return json( '日期错误！' );

        $view = '';
        if ( !empty( $all[ 'view' ] ) )
        $view = $all[ 'view' ];
        $st = !empty( $all[ 'status' ] ) ? $all[ 'status' ] : $status;

        //默认查询
        $query = Db::table( 'order' );
        if ( $st ) {
            $query->where( 'status', 'in', $st );
        }

        $query_arr = [];
        //处理分页其它参数

        //部门权限
        // $dept = new Dept();
        // $my_depts = $dept->getMyDepts( $uid );
        // $arr = [];
        // $dept_id = '';
        // foreach ( $my_depts as $dept ) {
        //$arr[] = $dept[ 'id' ];
    //}
    // if ( !empty( $all[ 'dept_id' ] ) ) {
    //     $dept_id = $all[ 'dept_id' ];
    //     if ( in_array( $dept_id, $arr ) ) {
    //         $arr = [ $dept_id ];
    //     } else {
    //         $arr = [];
    //     }
    // }
    // $my_depts = implode( ',', $arr );
    // $query->where( 'dept_id', 'in', $my_depts );

    //类型
    $type = '';
    if ( !empty( $all[ 'type' ] ) ) {
        $type = $all[ 'type' ];
        $query->where( 'type', $all[ 'type' ] );
        $query_arr[ 'type' ] = $all[ 'type' ];
    }

    $goods_name='';
    if(!empty($all['goods_name'])){
        $goods_name=trim($all['goods_name']);
        $query->where('goods_list','like','%'.$goods_name."%");
        $query_arr['goods_name']= $goods_name;
    }


    $po = '';
    if ( !empty( $all[ 'po' ] ) ) {
        $po = trim( $all[ 'po' ] );
        $query->where( 'order_no', 'like', '%' . $po . '%' );
        $query_arr[ 'po' ] = $all[ 'po' ];
    }
    $customer_id = '';
    if ( !empty( $all[ 'customer' ] ) ) {
        $customer_id = trim( $all[ 'customer' ] );
        $query->where( 'customer_id', $customer_id );
        $query_arr[ 'customer' ] = $customer_id;
    }

    if ( !empty( $all[ 'sdate' ] ) ) {
        $query->where( 'create_time', '>=', trim( $sdate ) );
        $query_arr[ 'sdate' ] = $all[ 'sdate' ];
    }

    if ( !empty( $all[ 'edate' ] ) ) {
        $query->where( 'create_time', '<=', trim( $edate ).' 23:59:59' );
        $query_arr[ 'edate' ] = $all[ 'edate' ];
    }

    $list = $query->order( 'id desc' )->paginate( 15 )->toArray();
    $num_deliv = 0;
    $num_undeliv = 0;

    $query2 = '&'.http_build_query( $query_arr );

    foreach ( $list[ 'data' ] as &$kv ) {
        $kv[ 'status_name' ] = $this->status[ $kv[ 'status' ] ];
        $kv[ 'customer_id_name' ] = Db::table( 'customer' )->where( 'id', $kv[ 'customer_id' ] )->value( 'name' );
        $kv[ 'sales_name' ] = $this->users[ $kv[ 'sales_id' ] ][ 'name' ];
        $kv[ 'amount' ] = number_format( $kv[ 'amount' ], 4 );
        $kv[ 'days_left' ] = common::time_format( strtotime( $kv[ 'delivery_date' ] )-time() );

        //本订单已发货数量
        $sum_delivery = Db::query( 'select sum(qty) as qty from delivery_list where delivery_id in(select id from delivery where status=2 and order_id=?)', [ $kv[ 'id' ] ] );
        $kv[ 'delivered_qty' ] = ( $sum_delivery[ 0 ][ 'qty' ] )?:0 ;
        $kv[ 'undelivered_qty' ] = $kv[ 'qty' ]-$kv[ 'delivered_qty' ];
        //$kv[ 'undelivered_qty' ] = $kv[ 'undelivered_qty' ] >= 0?:'超'.abs( $kv[ 'undelivered_qty' ] );

        if ( $kv[ 'delivered_qty' ]>0 ) {
            if ( $kv[ 'delivered_qty' ] >= $kv[ 'qty' ] ) {
                //全部交完或超交
                $kv[ 'status' ] = 4;
            } else {
                $kv[ 'status' ] = 3;
            }
            Db::table( 'order' )->save( $kv );
        }
    }

    //halt( $this->type );
    $sys = Session::get( 'sys' );
    $custs = Db::table( 'customer' )->where( 'status', 1 )->column( 'id,name' );

    View::assign( [
        'sys' => $sys,
        'list' => $list,
        'customer_list' => $custs,
        'customer' => $customer_id,
        'dept' => $this->dept,
        // 'dept_id'=>$dept_id,
        'status_list' => $this->status,
        'status' => $st,
        'types' => $this->type,
        'type' => $type,
        'po' => $po,
        'goods_name' =>$goods_name,
        'sdate'=>$sdate,
        'edate'=>$edate,
        'currency_symbol' => $this->sys[ 'currency_symbol' ],
        'query'=>$query2
    ] );

    return View::fetch( $view );

}

//订单流程操作, 传入id, status

public function order_check() {
    $uid = Session::get( 'logonid' );
    if ( !$uid )
    header( 'location:/index.php/login' );
    $all = Request::param();

    if ( empty( $all[ 'table' ] ) || empty( $all[ 'id' ] ) || empty( $all[ 'status' ] ) ) {
        return json( [ 'code' => 0, 'msg' => '无效的状态！' ] );
    }

    $res = Db::execute( 'update `'.$all[ 'table' ].'` set status=?,check_time=?,check_by=? where id=?', [ $all[ 'status' ], date( 'Y-m-d H:i:s' ), $uid, $all[ 'id' ] ] );

    return json( [ 'code' => $res ] );

}

//订单操作记录

public function order_log() {
    if ( !Session::get( 'logonid' ) )
    header( 'location:/index.php/login' );

    $all = Request::param();
    if ( empty( $all[ 'id' ] ) )
    return 'Invalid order id!';
    $id = $all[ 'id' ];

    $order = Db::table( 'order' )->find( $id );
    if ( !$order )
    return '无效的订单！';
    $order[ 'creater_name' ] = $this->users[ $order[ 'creater' ] ][ 'name' ];
    $order[ 'status_name' ] = $this->status[ $order[ 'status' ] ];

    $list = Db::table( 'order_log' )->where( 'order_id', $id )->select()->toArray();
    foreach ( $list as &$log ) {
        if ( $log[ 'creater' ] )
        $log[ 'creater_name' ] = $this->users[ $log[ 'creater' ] ][ 'name' ];
    }

    View::assign( [ 'order' => $order, 'list' => $list ] );
    return View::fetch( 'order_log' );
}

public function order_flow() {
    $sys = Db::table( 'sys' )->find( 1 );
    View::assign( [ 'list' => $this->status, 'sys' => $sys ] );
    return View::fetch();
}

public function get_status() {
    $uid = Session::get( 'logonid' );
    if ( !$uid ) {
        return header( 'location:/index.php/login/customer_login' );
    }

    return json_encode( [ 'code' => 1, 'status' => $this->status ] );
}

//商品单下单

public function order_add() {
    $uid = Session::get( 'logonid' );
    if ( empty( $uid ) )
    header( 'location:/index.php/login/target/admin' );
    $all = Request::param();

    //无商品参数提交，表示是进入页面
    if ( empty( $all[ 'goods' ] ) ) {
        $custs = Db::table( 'customer' )->where( 'status', 1 )->order( 'id' )->column( 'id,name,name2' );
        $goods = Db::table( 'goods' )->where( 'status', 1 )->column( 'id,name,price,cat_id' );
        $specs = Db::table( 'specs' )->where( 'status', 1 )->column( 'id,name,goods_id' );
        $sales = Db::query( "select id,name from user where status=1 and id<>1 and (group_id=1 or group_id in(select id from user_group where status=1 and name like '%销售%'))" );

        View::assign( [
            'cats'=>$this->cat,
            'custs' => $custs,
            'goods' => $goods,
            'sales' => $sales,
            'specs' => $specs

        ] );
        return View::fetch();
    }

    //处理商品, 价格
    $price = 0;
    $goods_list_str = [];
    $order_list = [];
    $qty = 0;

    if ( empty( $all[ 'customer_id' ] ) || empty( $all[ 'sales_id' ] ) ) {
        return json( [ 'code' => 0, 'msg' => '客户或者业务负责人未选择！' ] );
    }
    $order_no = trim( $all[ 'customer_order_no' ] );
    if ( Db::table( 'order' )->where( 'order_no', 'like', $order_no )->find() ) {
        return json( [ 'code' => 0, 'msg' => '客户订单已存在于系统中！' ] );
    }

    foreach ( $all[ 'goods' ] as $goods ) {
        $goods_db = Db::table( 'goods' )->find( $goods[ 'goods_id' ] );
        $goods[ 'name' ] = $goods_db[ 'name' ];
        //如果有规格就用规格参数，否则就用商品基本参数。
        if ( !empty( $goods[ 'id' ] ) ) {
            $goods_sp = Db::table( 'specs' )->find( $goods[ 'id' ] );
            $goods[ 'name' ] .= ( '【' . $goods_sp[ 'name' ] . '】' );
            $goods_db[ 'price' ] = $goods_sp[ 'price' ];
        }
        //商品价格小计
        $gprice = $goods_sp[ 'price' ] * $goods[ 'qty' ];

        $str = $goods[ 'name' ] . 'x' . $goods[ 'qty' ];
        $goods_list_str[] = $str;
        //商品列表
        $price += $gprice;
        //商品价格
        $qty += $goods[ 'qty' ];

        //订单商品表
        $order_list[] = array(
            'goods_id' => $goods[ 'goods_id' ],
            'name' => $goods[ 'name' ],
            'specs_id' => $goods[ 'id' ],
            'price' => $goods_db[ 'price' ],
            'qty' => $goods[ 'qty' ],
            'total' => $gprice,
            'create_time' => date( 'Y-m-d H:i:s' ),
            'memo' => $goods[ 'memo' ],
            'creater' => $uid
        );

    }

    $goods_list_str = implode( ',', $goods_list_str );

    //取得新的流水号order
    $om = new OrderModel();

    //准备订单内容，写入订单并取得id号
    $row = array(
        'type' => 1,
        'order_no' => str_replace( '－', '-', trim( $all[ 'customer_order_no' ] ) ),
        'contact' => trim( $all[ 'contact' ] ),
        'mobile' => trim( $all[ 'mobile' ] ),
        'delivery_date' => $all[ 'delivery_date' ],
        'sales_id' => $all[ 'sales_id' ],
        'create_time' => date( 'Y-m-d H:i:s' ),
        'qty' => $qty,
        'amount' => $price,
        'in_stock' => $all[ 'in_stock' ],
        'status' => 1,
        'customer_id' => $all[ 'customer_id' ],
        'goods_list' => $goods_list_str,
        'memo' => trim( $all[ 'memo' ] ),
        'dept_id' => 1
    );

    $order_id = $om->insertGetId( $row );

    //写入订单日志表
    $res = Db::table( 'order_log' )->insert( array(
        'order_id' => $order_id,
        'name' => 'PO#:' . $row[ 'order_no' ],
        'creater' => 2,
        'create_time' => date( 'Y-m-d H:i:s', time() )
    ) );

    //写入订单明细表
    foreach ( $order_list as &$row ) {
        $row[ 'order_id' ] = $order_id;
        //Db::execute( 'delete from cart where customer_id=? and specs_id=?', [ $customer[ 'id' ], $row[ 'specs_id' ] ] );
    }
    Db::table( 'order_list' )->insertAll( $order_list );

    return json( [ 'code' => $res, 'msg' => '下单成功!' ] );
}

//订单明细表

public function order_list() {
    $uid = Session::get( 'logonid' );
    $all = Request::param();

    //无商品参数提交，表示是进入页面
    if ( empty( $all[ 'id' ] ) || empty( $uid ) ) {
        return json( [ 'code' => 0, 'msg' => '错误，请登录后重试！' ] );
    }

    $order = Db::table( 'order' )->find( $all[ 'id' ] );
    //halt( $this->users[ $order[ 'creater' ] ][ 'name' ] );
    $order[ 'creater_name' ] = $this->users[ $order[ 'creater' ] ][ 'name' ];
    $order[ 'sales_name' ] = $this->users[ $order[ 'sales_id' ] ][ 'name' ];
    $order[ 'status_name' ] = $this->status[ $order[ 'status' ] ][ 0 ];

    $list = Db::table( 'order_list' )->where( 'order_id', $all[ 'id' ] )->select()->toArray();
    $num = 0;
    $sum = 0;
    $num_deliv = 0;
    $num_undeliv = 0;
    foreach ( $list as &$kv ) {
        $kv[ 'unit' ] = Db::table( 'goods' )->where( 'id', $kv[ 'goods_id' ] )->value( 'unit' );
        $num += $kv[ 'qty' ];
        $sum += $kv[ 'total' ];
        $kv[ 'price' ] = number_format( $kv[ 'price' ], 4 );
        $kv[ 'total' ] = number_format( $kv[ 'total' ], 4 );

        //本规格已发货数量
        $sum_delivery = Db::query( 'select sum(qty) as qty from delivery_list where delivery_id in(select id from delivery where status=2 and order_id=?) and specs_id=?', [ $kv[ 'order_id' ], $kv[ 'specs_id' ] ] );
        $kv[ 'delivery_qty' ] = ( $sum_delivery[ 0 ][ 'qty' ] )?:0 ;
        $num_deliv += $kv[ 'delivery_qty' ];
        $kv[ 'undelivery_qty' ] = $kv[ 'qty' ]-$kv[ 'delivery_qty' ];
        $num_undeliv += $kv[ 'undelivery_qty' ];
    }

    View::assign( [
        'order' => $order,
        'list' => $list,
        'sys' => $this->sys,
        'num' => $num,
        'sum' => number_format( $sum, 4 ),
        'num_deliv'=>$num_deliv,
        'num_undeliv'=>$num_undeliv,
        'date'=>date( 'Y-m-d' ),
        'uname'=>Session::get( 'uname' ),

    ] );

    return View::fetch( 'order/order_list' );

}

//客户欠料统计

public function customer_order_list() {

    $uid = Session::get( 'logonid' );
    $all = Request::param();

    if ( empty( $uid ) ) {
        return json( [ 'code' => 0, 'msg' => '请登录！' ] );
    }

    $orders = Db::table( 'order' );

    $customer_id = '';
    if ( !empty( $all[ 'customer_id' ] ) ) {
        $customer_id = Db::table( 'customer' )->where( 'id', $all[ 'customer_id' ] )->value( 'id' );
        $orders->where( 'customer_id', $customer_id );
    }
    $query_arr[ 'customer_id' ] = $customer_id;

    $sdate = !empty( $all[ 'sdate' ] ) ? $all[ 'sdate' ] : '';
    $edate = !empty( $all[ 'edate' ] ) ? $all[ 'edate' ] : date( 'Y-m-d', time() );
    if ( $edate < $sdate )
    return json( '日期错误！' );

    //默认查询
    // if ( empty( $all[ 'sdate' ] ) && empty( $all[ 'edate' ] ) && empty( $all[ 'po' ] ) ) {
    //     $orders->where( 'create_time', 'between', [ $sdate, $edate ] );
    // }

    $po = '';
    if ( !empty( $all[ 'po' ] ) ) {
        $po = trim( $all[ 'po' ] );
        $orders->where( 'order_no', 'like', '%' . $po . '%' );
        $query_arr[ 'po' ] = $all[ 'po' ];
    }

    if ( !empty( $all[ 'sdate' ] ) ) {
        $orders->where( 'create_time', '>=', trim( $sdate ) );
        $query_arr[ 'sdate' ] = $all[ 'sdate' ];
    }

    if ( !empty( $all[ 'edate' ] ) ) {
        $orders->where( 'create_time', '<=', trim( $edate ).' 23:59:59' );
        $query_arr[ 'edate' ] = $all[ 'edate' ];
    }

    if ( !empty( $all[ 'excel' ] ) ) {
        $orders = $orders->order( 'create_time' )->select()->toArray();
        $tmp = $orders;
        $orders = [];
        $orders[ 'data' ] = $tmp;
        $tmp = null;
    } else {
        $orders = $orders->order( 'create_time' )->paginate( 10 )->toArray();
    }

    $query2 = '&'.http_build_query( $query_arr );

    //订单数据处理
    $sn = 1;
    foreach ( $orders[ 'data' ] as &$order ) {
        $order[ 'customer_name' ] = Db::table( 'customer' )->where( 'id', $order[ 'customer_id' ] )->value( 'name' );
        $order[ 'creater_name' ] = $this->users[ $order[ 'creater' ] ][ 'name' ];
        $order[ 'sales_name' ] = $this->users[ $order[ 'sales_id' ] ][ 'name' ];
        $order[ 'status_name' ] = $this->status[ $order[ 'status' ] ][ 0 ];

        $order[ 'goods_list' ] = Db::table( 'order_list' )->where( 'order_id', $order[ 'id' ] )->select()->toArray();
        $order[ 'goods_count' ] = count( $order[ 'goods_list' ] );

        $num = 0;
        $sum = 0;
        $num_deliv = 0;
        $num_undeliv = 0;
        foreach ( $order[ 'goods_list' ] as &$kv ) {
            $kv[ 'sn' ] = ( $sn++ );
            $goods = Db::table( 'goods' )->where( 'id', $kv[ 'goods_id' ] )->column( 'unit,desc' );
            $kv[ 'unit' ] = $goods[ 0 ][ 'unit' ];
            $kv[ 'desc' ] = $goods[ 0 ][ 'desc' ];
            //$num += $kv[ 'qty' ];
            //$sum += $kv[ 'total' ];
            $kv[ 'price' ] = number_format( $kv[ 'price' ], 4 );
            $kv[ 'total' ] = number_format( $kv[ 'total' ], 4 );

            //本规格已发货数量
            $sum_delivery = Db::query( 'select sum(qty) as qty from delivery_list where delivery_id in(select id from delivery where status=2 and order_id=?) and specs_id=?', [ $kv[ 'order_id' ], $kv[ 'specs_id' ] ] );
            $kv[ 'delivery_qty' ] = ( $sum_delivery[ 0 ][ 'qty' ] )?:0 ;
            //$num_deliv += $kv[ 'delivery_qty' ];
            $kv[ 'undelivery_qty' ] = $kv[ 'qty' ]-$kv[ 'delivery_qty' ];
            //$num_undeliv += $kv[ 'undelivery_qty' ];
            //$kv[ 'undelivery_qty' ] = $kv[ 'undelivery_qty' ] >= 0?:'超'.abs( $kv[ 'undelivery_qty' ] );
        }

    }

    //halt( $orders[ 'data' ] );
    if ( !empty( $all[ 'excel' ] ) ) {
        $this->customer_order_list_csv( $orders[ 'data' ] );
        exit;
        //return json( [ 'code'=>1 ] );
    } else {
        $sys = Session::get( 'sys' );
        $custs = Db::table( 'customer' )->where( 'status', 1 )->column( 'id,name' );

        View::assign( [
            'list' => $orders,
            'customer_list' => $custs,
            'customer'=>$customer_id,
            'sys' => $this->sys,
            //'num' => $num,
            //'sum' => number_format( $sum, 4 ),
            //'num_deliv'=>$num_deliv,
            //'num_undeliv'=>$num_undeliv,
            'date'=>date( 'Y-m-d' ),
            'sdate'=>$sdate,
            'edate'=>$edate,
            'uname'=>Session::get( 'uname' ),
            'po' => $po,
            'currency_symbol' => $this->sys[ 'currency_symbol' ],
            'query'=>$query2

        ] );
        return View::fetch();
    }

}

//订单删除

public function order_cancel( $table = '', $id = '' ) {
    $uid = Session::get( 'logonid' );
    if ( empty( $uid ) )
    return json( [ 'code' => 0, 'msg' => '登录已过期' ] );

    $all = Request::param();

    if ( empty( $all[ 'id' ] ) || empty( $all[ 'table' ] ) ) {
        return json( [ 'code' => 0, 'msg' => '参数不正确' ] );
    }
    $name = !empty( $all[ 'name' ] )?$all[ 'name' ]:'订单删除';
    $res = common::row_del( $all[ 'table' ], $all[ 'id' ], $name );

    return $res;
}

//出货单管理

public function delivery() {
    $uid = Session::get( 'logonid' );
    if ( empty( $uid ) )
    return json( [ 'code' => 0, 'msg' => '登录已过期' ] );

    $all = Request::param();
    $sdate = !empty( $all[ 'sdate' ] ) ? $all[ 'sdate' ] : '';
    $edate = !empty( $all[ 'edate' ] ) ? $all[ 'edate' ] : date( 'Y-m-d 23:59:59', time() );
    if ( $edate < $sdate )
    return json( '日期错误！' );

    //默认查询
    $query = Db::table( 'delivery' );
    //默认查询
    if ( empty( $all[ 'sdate' ] ) && empty( $all[ 'edate' ] ) && empty( $all[ 'po' ] ) ) {
        $query->where( 'create_time', 'between', [ $sdate, $edate ] );
    }

    $po = '';
    if ( !empty( $all[ 'po' ] ) ) {
        $po = trim( $all[ 'po' ] );
        $query->where( 'order_id in(select id from `order` where order_no like ?)', [ '%' . $po . '%' ] );
    }

    $customer_id = '';
    if ( !empty( $all[ 'customer' ] ) ) {
        $customer_id = trim( $all[ 'customer' ] );
        $query->where( 'customer_id', $customer_id );
    }

    if ( !empty( $all[ 'sdate' ] ) ) {
        $query->where( 'create_time', '>=', trim( $sdate ) );
    }
    if ( !empty( $all[ 'edate' ] ) ) {
        $query->where( 'create_time', '<=', trim( $edate ) );
    }

    $list = $query->order( 'id desc' )->paginate( 15 )->toArray();
    //halt( $this->users );

    foreach ( $list[ 'data' ] as &$kv ) {
        $kv[ 'order_no' ] = Db::table( 'order' )->where( 'id', $kv[ 'order_id' ] )->value( 'order_no' );
        $kv[ 'customer_id_name' ] = Db::table( 'customer' )->where( 'id', $kv[ 'customer_id' ] )->value( 'name' );
        $kv[ 'status_name' ] = $this->status_delivery[ $kv[ 'status' ] ];
        $kv[ 'creater_name' ] = $this->users[ $kv[ 'creater' ] ][ 'name' ];
    }
    //$sys = Session::get( 'sys' );
    $custs = Db::table( 'customer' )->where( 'status', 1 )->column( 'id,name' );

    View::assign( [
        'customer_list' => $custs,
        'customer' => $customer_id,
        'po' => $po,
        'currency_symbol' => $this->sys[ 'currency_symbol' ],
        'list' => $list
    ] );

    return View::fetch();
}

//出货单录入

public function delivery_add() {
    $uid = Session::get( 'logonid' );
    if ( empty( $uid ) )
    return json( [ 'code' => 0, 'msg' => '登录已过期' ] );
    $all = Request::param();

    if ( empty( $all[ 'goods' ] ) ) {
        $order_list = Db::table( 'order' )->where( 'status', 'in', '2,3' )->order( 'order_no' )->column( 'id,order_no' );
        $specs = Db::table( 'specs' )->where( 'status', 'x' )->column( 'id,name,goods_id' );

        foreach ( $specs as &$sp ) {

        }

        View::assign( [
            'order_list' => $order_list,
            'specs' => $specs

        ] );
        return View::fetch();
    }

    //halt( $all );
    //处理商品, 价格
    $price = 0;
    $order_list = [];
    $qty = 0;

    if ( empty( $all[ 'order_no' ] ) || empty( $all[ 'driver_name' ] ) ) {
        return json( [ 'code' => 0, 'msg' => '订单、司机信息未输入！' ] );
    }

    $order = Db::table( 'order' )->where( 'order_no', $all[ 'order_no' ] )->find();

    foreach ( $all[ 'goods' ] as $goods ) {
        $goods_db = Db::table( 'goods' )->find( $goods[ 'goods_id' ] );
        $goods[ 'name' ] = $goods_db[ 'name' ];
        $goods_sp = Db::table( 'specs' )->find( $goods[ 'id' ] );
        $goods[ 'name' ] .= ( '【' . $goods_sp[ 'name' ] . '】' );
        $goods_db[ 'price' ] = $goods_sp[ 'price' ];

        //商品价格小计
        $gprice = $goods_sp[ 'price' ] * $goods[ 'qty' ];
        $price += $gprice;
        //商品价格
        $qty += $goods[ 'qty' ];

        //订单商品表
        $order_list[] = array(
            'goods_id' => $goods[ 'goods_id' ],
            'name' => $goods[ 'name' ],
            'specs_id' => $goods[ 'id' ],
            'price' => $goods_db[ 'price' ],
            'qty' => $goods[ 'qty' ],
            'pack_qty' => $goods[ 'pack_qty' ],
            'qty_of_pack' => $goods[ 'qty_of_pack' ],
            'total' => $gprice,
            'create_time' => date( 'Y-m-d H:i:s' ),
            'memo' => $goods[ 'memo' ],
            'creater' => $uid
        );
    }

    //准备交货单内容，写入订单并取得id号
    $row = array(
        'order_id' => $order[ 'id' ],
        'customer_id' => Db::table( 'order' )->where( 'id', $order[ 'id' ] )->value( 'customer_id' ),
        'driver_mobile' => trim( $all[ 'driver_mobile' ] ),
        'driver_name' => trim( $all[ 'driver_name' ] ),
        'create_time' => date( 'Y-m-d H:i:s' ),
        'creater' => $uid,
        'qty' => $qty,
        'amount' => $price,
        'status' => 1,
        'memo' => trim( $all[ 'memo' ] )
    );

    $om = new DeliveryModel();
    $delivery_id = $om->insertGetId( $row );

    //更新订单已交数
    Db::execute( 'update `order` set delivered_qty=delivered_qty+? where id=?', [ $qty, $order[ 'id' ] ] );

    //写入订单明细表
    foreach ( $order_list as &$row ) {
        $row[ 'delivery_id' ] = $delivery_id;
    }
    $res = Db::table( 'delivery_list' )->insertAll( $order_list );

    return json( [ 'code' => $res, 'msg' => '交货单保存成功!' ] );
}

//发货明细表

public function delivery_list() {
    $uid = Session::get( 'logonid' );
    $all = Request::param();

    //无商品参数提交，表示是进入页面
    if ( empty( $all[ 'id' ] ) || empty( $uid ) ) {
        return json( [ 'code' => 0, 'msg' => '错误，请登录后重试！' ] );
    }

    //halt( $all[ 'ids' ] );
    if ( empty( $all[ 'ids' ] ) ) $all[ 'ids' ] = $all[ 'id' ];

    $list = Db::table( 'delivery_list' )->where( 'delivery_id', 'in', $all[ 'ids' ] )->order( 'delivery_id' )->select()->toArray();
    $num = 0;
    $pack_num = 0;
    $customer = '';

    foreach ( $list as &$kv ) {
        $delivery = Db::table( 'delivery' )->find( $kv[ 'delivery_id' ] );
        $order = Db::table( 'order' )->find( $delivery[ 'order_id' ] );
        $kv[ 'po' ] = $order[ 'order_no' ];
        if ( $customer == '' ) {
            $customer = Db::table( 'customer' )->where( 'id', $order[ 'customer_id' ] )->column( 'name,mobile' );
            $customer = $customer[ 0 ];
        }

        $kv[ 'creater_name' ] = $this->users[ $order[ 'creater' ] ][ 'name' ];
        $kv[ 'sales_name' ] = $this->users[ $order[ 'sales_id' ] ][ 'name' ];
        $kv[ 'status_name' ] = $this->status[ $order[ 'status' ] ][ 0 ];

        $arr = Db::table( 'goods' )->where( 'id', $kv[ 'goods_id' ] )->column( 'name,desc' );
        $kv[ 'goods_id_name' ] = $arr[ 0 ][ 'name' ];
        $kv[ 'goods_id_desc' ] = $arr[ 0 ][ 'desc' ];
        $kv[ 'specs_id_name' ] = Db::table( 'specs' )->where( 'id', $kv[ 'specs_id' ] )->value( 'name' );

        //$pack_num += $kv[ 'pack_qty' ];
        //$num += $kv[ 'qty' ];
        //$kv[ 'qty' ] = $kv[ 'qty' ];

    }

    //halt( $list );
    View::assign( [ 'order' => $order, 'delivery'=>$delivery, 'delivery_date'=>date( 'Y-m-d H:i:s' ), 'list' => $list, 'currency_symbol' => $this->sys[ 'currency_symbol' ], 'customer'=>$customer, 'num' => $num, 'sys'=>$this->sys, 'user'=>$this->users[ $uid ] ] );

    return View::fetch( 'order/delivery_list' );

}

//订单详情

public function order_detail() {
    $uid = Session::get( 'logonid' );
    if ( empty( $uid ) )
    return json( [ 'code' => 0, 'msg' => '登录已过期' ] );

    $all = Request::param();

    if ( empty( $all[ 'id' ] ) && empty( $all[ 'order_no' ] ) ) {
        return json( [ 'code' => 0, 'msg' => '订单id参数!' ] );
    }

    if ( !empty( $all[ 'id' ] ) ) {
        $order = Db::table( 'order' )->find( $all[ 'id' ] );
    } elseif ( !empty( $all[ 'order_no' ] ) ) {
        $order = Db::table( 'order' )->where( 'order_no', $all[ 'order_no' ] )->find();
    }
    if ( !$order ) {
        return json( [ 'code'=>0, 'msg'=>'Order ['.$all[ 'order_no' ].'] not found!' ] );
    }

    // halt( $all );
    unset( $order[ 'goods_list' ] );
    //商品描述一栏不要了
    if ( !empty( $all[ 'detail' ] ) ) {
        $order[ 'order_list' ] = Db::table( 'order_list' )->where( 'order_id', $order[ 'id' ] )->select()->toArray();
        foreach ( $order[ 'order_list' ] as &$kv ) {
            $kv[ 'goods_id_name' ] = Db::table( 'goods' )->where( 'id', $kv[ 'goods_id' ] )->value( 'name' );
            $spec_row = Db::table( 'specs' )->where( 'id', $kv[ 'specs_id' ] )->column( 'name,storage' );
            $kv[ 'specs_id_name' ] = $spec_row[ 0 ][ 'name' ];
            $kv[ 'storage' ] = $spec_row[ 0 ][ 'storage' ];

            $sum_delivery = Db::query( 'select sum(qty) as qty from delivery_list where delivery_id in(select id from delivery where status=2 and order_id=?) and specs_id=?', [ $kv[ 'order_id' ], $kv[ 'specs_id' ] ] );
            $kv[ 'delivery_qty' ] = ( $sum_delivery[ 0 ][ 'qty' ] )?:0 ;
            //$num_deliv += $kv[ 'delivery_qty' ];
            $kv[ 'undelivery_qty' ] = $kv[ 'qty' ]-$kv[ 'delivery_qty' ];
            //$num_undeliv += $kv[ 'undelivery_qty' ];
        }

    }

    if ( !empty( $all[ 'delivered_qty' ] ) ) {
        //$order[ 'delivery_qty' ] = Db::query( 'select sum(qty) as qty from delivery where order_id=? and status=2', [ $all[ 'id' ] ] )[ 0 ][ 'qty' ];
        //if ( !$order[ 'delivery_qty' ] ) $order[ 'delivery_qty' ] = 0;
        //halt( $order[ 'delivery_qty' ][ 0 ][ 'qty' ] );
    }
    return json( [ 'code' => 1, 'data' => $order ] );

}

//出货统计

public function delivery_analyze() {
    $uid = Session::get( 'logonid' );
    if ( empty( $uid ) )
    return json( [ 'code' => 0, 'msg' => '登录已过期' ] );

    $all = Request::param();

    $sdate = !empty( $all[ 'sdate' ] ) ? $all[ 'sdate' ] : '';
    $edate = !empty( $all[ 'edate' ] ) ? $all[ 'edate' ].' 23:59:59' : date( 'Y-m-d 23:59:59', time() );
    if ( $edate < $sdate )
    return json( '日期错误！' );

    //echo dump( $all );
    //echo $edate;

    //默认查询
    $query = Db::table( 'order' );

    $po = '';
    if ( !empty( $all[ 'po' ] ) ) {
        $po = trim( $all[ 'po' ] );
        $query->whereRaw( 'order_no like ?', [ '%' . $po . '%' ] );
    }

    $customer_id = '';
    if ( !empty( $all[ 'customer' ] ) ) {
        $customer_id = trim( $all[ 'customer' ] );
        $query->where( 'customer_id', $customer_id );
    }

    $list = $query->limit( 9 )->order( 'id' )->select()->toArray();

    foreach ( $list as &$kv ) {
        $customer = Db::table( 'customer' )->find( $kv[ 'customer_id' ] );
        $kv[ 'customer_name' ] = $customer[ 'name' ];
        $kv[ 'customer_address' ] = $customer[ 'address' ];

        $kv[ 'status_name' ] = $this->status[ $kv[ 'status' ] ];
        $kv[ 'creater_name' ] = $this->users[ $kv[ 'creater' ] ][ 'name' ];

        $d_list = Db::table( 'delivery_list' );

        //日期限制
        if ( !empty( $all[ 'sdate' ] ) ) {
            $d_list->where( 'create_time', '>=', trim( $sdate ) );
        }
        if ( !empty( $all[ 'edate' ] ) ) {
            $d_list->where( 'create_time', '<=', trim( $edate ) );
        }

        $d_list->whereRaw( 'delivery_id in(select id from delivery where `status`=2 and order_id=?)', [ $kv[ 'id' ] ] );

        $kv[ 'list' ] = $d_list->select()->toArray();
        if ( count( $kv[ 'list' ] ) ) {
            $kv[ 'list_sum' ] = 0;
            foreach ( $kv[ 'list' ] as &$item ) {
                $goods = Db::table( 'goods' )->find( $item[ 'goods_id' ] );
                $item[ 'goods_id_name' ] = $goods[ 'name' ];
                $item[ 'unit' ] = $goods[ 'unit' ];
                $item[ 'specs_id_name' ] = Db::table( 'specs' )->where( 'id', $item[ 'specs_id' ] )->value( 'name' );
                $amount = $item[ 'qty' ]*$item[ 'price' ];
                $item[ 'price' ] = number_format( $item[ 'price' ], 4 );
                $item[ 'amount' ] = number_format( $amount, 4 );
                $kv[ 'list_sum' ] += $amount;
            }
            $kv[ 'list_sum' ] = number_format( $kv[ 'list_sum' ], 3 );
        } else {
            $kv[ 'list_sum' ] = 0;
        }

    }
    //$sys = Session::get( 'sys' );
    $custs = Db::table( 'customer' )->where( 'status', 1 )->column( 'id,name' );

    //halt( $list );

    View::assign( [
        'customer_list' => $custs,
        'customer' => $customer_id,
        'po' => $po,
        'sdate' =>substr( $sdate, 0, 10 ),
        'edate' =>substr( $edate, 0, 10 ),
        'currency_symbol' => $this->sys[ 'currency_symbol' ],
        'list' => $list,
        'sys'=>$this->sys
    ] );

    return View::fetch();
}

//出货统计导出excel

public function order_delivery_csv() {
    $uid = Session::get( 'logonid' );
    if ( empty( $uid ) )
    return json( [ 'code' => 0, 'msg' => '登录已过期' ] );

    $all = Request::param();

    $sdate = !empty( $all[ 'sdate' ] ) ? $all[ 'sdate' ] : '';
    $edate = !empty( $all[ 'edate' ] ) ? $all[ 'edate' ].' 23:59:59' : date( 'Y-m-d 23:59:59', time() );
    if ( $edate < $sdate )
    return json( '日期错误！' );

    if ( empty( $all[ 'order_id' ] ) ) {
        return json( [ 'code' => 0, 'msg' => '无订单！' ] );
    } else {
        $order = Db::table( 'order' )->find( $all[ 'order_id' ] );
    }

    $customer = Db::table( 'customer' )->find( $order[ 'customer_id' ] );
    $order[ 'customer_name' ] = $customer[ 'name' ];
    $order[ 'customer_address' ] = $customer[ 'address' ];

    $order[ 'status_name' ] = $this->status[ $order[ 'status' ] ];
    $order[ 'creater_name' ] = $this->users[ $order[ 'creater' ] ][ 'name' ];

    $d_list = Db::table( 'delivery_list' );

    //日期限制
    if ( !empty( $all[ 'sdate' ] ) ) {
        $d_list->where( 'create_time', '>=', trim( $sdate ) );
    }
    if ( !empty( $all[ 'edate' ] ) ) {
        $d_list->where( 'create_time', '<=', trim( $edate ) );
    }

    $d_list->whereRaw( 'delivery_id in(select id from delivery where `status`=2 and order_id=?)', [ $order[ 'id' ] ] );

    $order[ 'list' ] = $d_list->select()->toArray();

    if ( count( $order[ 'list' ] ) ) {
        $order[ 'list_sum' ] = 0;
        foreach ( $order[ 'list' ] as &$item ) {
            $goods = Db::table( 'goods' )->find( $item[ 'goods_id' ] );
            $item[ 'goods_id_name' ] = $goods[ 'name' ];
            $item[ 'unit' ] = $goods[ 'unit' ];
            $item[ 'specs_id_name' ] = Db::table( 'specs' )->where( 'id', $item[ 'specs_id' ] )->value( 'name' );
            $item[ 'price' ] = $item[ 'price' ];
            $item[ 'amount' ] =  $item[ 'total' ];
            $order[ 'list_sum' ] += $item[ 'total' ];
        }
        $order[ 'list_sum' ] = number_format( $order[ 'list_sum' ], 4 );
    } else {
        $order[ 'list_sum' ] = 0;
    }

    $cols = [ 'delivery_id', 'create_time', 'goods_id_name', 'specs_id_name', 'qty', 'unit', 'price', 'total', 'memo' ];

    //dump( $order );

    $sys = Db::table( 'sys' )->find( 1 );
    $comp_name = $sys[ 'company_name' ];
    $comp_address = $sys[ 'address' ];

    $headlist = array(
        'names' => array( 'To:'.$order[ 'customer_name' ], '', '', '', 'From:'.$comp_name ),
        'address'=> array( 'Address:'.$order[ 'customer_address' ], '', '', '', 'Address:'.$comp_address ),
        'title' =>array( '送货单号', '出货时间', '图纸编号 Item', '品名规格 Specs', '数量 Qty', '单位 Unit', '单价 Price(USD)', '金额 Amount', '备注' )

    );
    echo common::excel_csv( $headlist, $cols, $order[ 'list' ], [], [ '', '', '', '', '', '', '' ], '出货统计' );

}

//出货单导出excel

public function delivery_list_csv() {
    $uid = Session::get( 'logonid' );
    if ( empty( $uid ) )
    return json( [ 'code' => 0, 'msg' => '登录已过期' ] );

    $all = Request::param();

    if ( empty( $all[ 'delivery_id' ] ) ) {
        return json( [ 'code' => 0, 'msg' => '无出货单！' ] );
    } else {
        $delivery = Db::table( 'delivery' )->find( $all[ 'delivery_id' ] );
    }

    $order = Db::table( 'order' )->find( $delivery[ 'order_id' ] );
    $customer = Db::table( 'customer' )->find( $order[ 'customer_id' ] );
    $delivery[ 'customer_name' ] = $customer[ 'name' ];
    $delivery[ 'customer_mobile' ] = $customer[ 'mobile' ];
    $delivery[ 'creater_name' ] = $this->users[ $delivery[ 'creater' ] ][ 'name' ];
    $delivery[ 'list' ] =  Db::table( 'delivery_list' )->where( 'delivery_id', $delivery[ 'id' ] )->select()->toArray();

    if ( count( $delivery[ 'list' ] ) ) {
        $delivery[ 'list_sum' ] = 0;
        foreach ( $delivery[ 'list' ] as &$item ) {
            $goods = Db::table( 'goods' )->find( $item[ 'goods_id' ] );
            $item[ 'in_stock' ] = $order[ 'in_stock' ];
            $item[ 'order_no' ] = $order[ 'order_no' ];
            $item[ 'goods_id_name' ] = $goods[ 'name' ];
            $item[ 'unit' ] = $goods[ 'unit' ];
            $item[ 'specs_id_name' ] = Db::table( 'specs' )->where( 'id', $item[ 'specs_id' ] )->value( 'name' );
            $amount = $item[ 'qty' ]*$item[ 'price' ];
            $item[ 'price' ] = number_format( $item[ 'price' ], 4 );
            $item[ 'amount' ] = $amount;
            $delivery[ 'list_sum' ] += $amount;
        }
        $delivery[ 'list_sum' ] = number_format( $delivery[ 'list_sum' ], 4 );
    } else {
        $delivery[ 'list_sum' ] = 0;
    }

    $cols = [ 'index', 'in_stock', 'order_no', 'goods_id_name', 'specs_id_name', 'qty_of_pack', 'pack_qty', 'qty', '', '', 'memo' ];

    $sys = Db::table( 'sys' )->find( 1 );
    $comp_name = $sys[ 'copy_right' ];
    $comp_address = $sys[ 'address' ];
    $comp_tel = $sys[ 'tel' ];
    $comp_email = $sys[ 'email' ];

    $headlist = array(
        'title'=>array( $comp_name, '\t\n' ),
        'address'=>array( '地址 Address:'.$comp_address, '\t\n' ),
        'tel_email'=>array( 'Tel:'.$sys[ 'tel' ], 'Email:'.$sys[ 'email' ], '\t\n' ),
        'costomer' => array( 'To:'.$delivery[ 'customer_name' ], 'Tel:'.$delivery[ 'customer_mobile' ], '', '', '送货单 Delivery Note (收货仓库一份，回执一份)', '\n' ),
        'header' =>array( '序号', '进仓编号 Warehourse', '合同编号Po#', '货号 Item', '名称及规格 Specs', 	'单件数量Qty/Pack', '件数 Packages', '数量小计 Qty', '实收件数', '实收数', '备注 Remark' ),

    );
    $foot = [
        '\n',
        '发货人 Consignor:'.$this->users[ $uid ][ 'name' ].'('.date( 'Y-m-d H:m' ).')',
        '\t\t\t\t\t\t\t\t',
        '收货日期 Date:', '\n\n',
        '司机Driver:'.$delivery[ 'driver_name' ].',Mobile:('.$delivery[ 'driver_mobile' ].')',
        '\t\t\t\t\t\t\t\t',
        '收货人 Consignee:' ];

        echo common::excel_csv( $headlist, $cols, $delivery[ 'list' ], $foot, [], '出货单' );

    }

    //发货欠货表

    public function customer_order_list_csv( $data ) {

        //halt( $data );
        $list  = [];
        foreach ( $data as $order ) {
            foreach ( $order[ 'goods_list' ] as $goods ) {
                $row = array(
                    'order_no'=>$order[ 'order_no' ],
                    'create_time'=>$order[ 'create_time' ],
                    'customer_name' =>$order[ 'customer_name' ],
                    'qty'=>$order[ 'qty' ],
                    'name'=>$goods[ 'name' ],
                    'desc'=>$goods[ 'desc' ],
                    'unit'=>'',
                    'goods_qty'=>$goods[ 'qty' ],
                    'delivery_qty'=>$goods[ 'delivery_qty' ],
                    'undelivery_qty'=>$goods[ 'undelivery_qty' ],
                    'price'=>$goods[ 'price' ],
                    'total'=>$goods[ 'total' ],
                    'memo'=>$goods[ 'memo' ]

                );
                $list[] = $row;
            }
        }
        unset( $data );

        $headlist = array(
            'title' => array( '客户发货欠货总表' ),
            'header' =>array( '订单PO#', '下单日期', '客户名称', '订单总数', '产品', '规格说明', '单位', '订购数量', '已发货', '待发货', '单价', '采购金额', '备注' )
        );

        $cols = [ 'order_no', 'create_time', 'customer_name', 'qty', 'name', 'desc', 'unit', 'goods_qty', 'delivery_qty', 'undelivery_qty', 'price', 'total', 'memo' ];

        echo common::excel_csv( $headlist, $cols, $list, [], [], '客户发货欠货统计表' );

    }

    public function excel_csv() {
        echo common::excel_csv( 1, 2, 3 );
    }

    //订单商品修改

    public function order_list_edit() {
        $uid = Session::get( 'logonid' );
        if ( empty( $uid ) )
        return json( [ 'code' => 0, 'msg' => '登录已过期' ] );

        $all = Request::param();

        if ( empty( $all[ 'id' ] ) ) {
            return json( [ 'code' => 0, 'msg' => '无产品记录数据！' ] );
        }

        if ( empty( $all[ 'qty' ] ) ) {
            return json( [ 'code' => 0, 'msg' => '无qty数据!' ] );
        }

        $row = Db::table( 'order_list' )->find( $all[ 'id' ] );
        if ( !$row ) {
            return json( [ 'code' => 0, 'msg' => '不明错误！' ] );
        }

        $order = Db::table( 'order' )->find( $row[ 'order_id' ] );

        if ( $order[ 'status' ] >= 4 ) {
            return json( [ 'code' => 0, 'msg' => '订单已完成，不能修改数据！' ] );
        }

        $data = array( 'id'=>$row[ 'id' ], 'qty'=>$all[ 'qty' ], 'total'=>$row[ 'price' ]*$all[ 'qty' ] );
        $res = Db::table( 'order_list' )->save( $data );

        if ( $res ) {
            $this->order_refresh( $order, '修改产品数,'.$row[ 'name' ].$row[ 'qty' ].'=>'.$all[ 'qty' ] );
        }

        return json( [ 'code' => $res, 'data'=>$all ] );

    }

    //重新计算订单的商号
    public function order_refresh( $order, $msg ) {
        if ( !$order ) return 0;
        $list = Db::table( 'order_list' )->where( 'order_id', $order[ 'id' ] )->select()->toArray();

        $total = 0;
        $qty = 0;

        foreach ( $list as $row ) {
            $qty += $row[ 'qty' ];
            $total += $row[ 'total' ];
        }

        $log = array( 'order_id'=>$order[ 'id' ], 'name'=>$msg, 'create_time'=>date( 'Y-m-d H:i:s' ), 'creater'=>2 );
        Db::table( 'order_log' )->insert( $log );

        $order[ 'amount' ] = $total;
        $order[ 'qty' ] = $qty;

        $res = Db::table( 'order' )->save( $order );

    }

}
